package cn.itcast.service;

import cn.itcast.entity.Result;
import cn.itcast.mobile.MobileOrderService;
import cn.itcast.mobile.PayLogService;
import cn.itcast.pojo.Order;
import cn.itcast.pojo.PayLog;
import cn.itcast.pojo.Setmeal;
import cn.itcast.utils.ConvertUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.wxpay.sdk.MyConfig;
import com.github.wxpay.sdk.WXPay;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Demo class
 *
 * @author gyc
 * @date 2021/10/18
 */
@Service
public class WxPayService {
    @Reference
    private MobileOrderService orderService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private PayLogService payLogService;

    public String sendQrCode(String orderId, HttpServletRequest request) {
        MyConfig config = new MyConfig();
        WXPay wxpay = null;
        try {
            wxpay = new WXPay(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //根据订单Id 查询订单
        Result result = orderService.findOrderById(orderId);
        Order order = (Order) result.getData();
        if (null == order){
            throw new NullPointerException("订单不存在!");
        }
        if ("1".equals(order.getPayStatus())){
            throw new NullPointerException("订单已结算或状态错误!");
        }
        //根据套餐id 查询商品金额 名称
        Setmeal setmeal = setmealService.findById(order.getSetmealId());
        String name = setmeal.getName();
        // 微信支付URL需要传入的金额单位是分，此处将订单金额转换成'分'单位
        String order_price = String.valueOf(setmeal.getPrice()*100);
        String out_trade_no = System.currentTimeMillis()+"";
        String trade_type = "NATIVE";
        //String notify_url = "http://dwxw.vip.aeert.com/pay/notify";
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", name);
        System.out.println("out_trade_no"+out_trade_no);
        data.put("out_trade_no", out_trade_no);//商户订单号
        data.put("total_fee", "1");
        //data.put("total_fee",order_price);
        //data.put("spbill_create_ip", ConvertUtils.localIp());
        data.put("spbill_create_ip", request.getRemoteAddr());
        data.put("notify_url", "http://2z6ntw.natappfree.cc/pay/notify");
        data.put("trade_type", trade_type);  // 此处指定为扫码支付
        try {
            Map<String, String> unifiedOrder = wxpay.unifiedOrder(data);
            String code = unifiedOrder.get("return_code");
            if (code.equals("SUCCESS")) {
                String code_url = unifiedOrder.get("code_url");
//                PayLog payLog = payLogService.findByOrderId(orderId);
//                if (payLog == null) {
                    PayLog payLog = new PayLog();
                    payLog.setOrderId(orderId);
                    payLog.setTransactionId(out_trade_no);
                    long time = System.currentTimeMillis();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    payLog.setPayTime(null);
                    payLog.setMoney(1.0);
                    payLog.setCreateTime(df.parse(df.format(time)));
                    payLog.setPayStatus(0);
                    payLogService.save(payLog);
                //}
                return code_url;
            }else{
                return "订单有误";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String payBack(Map<String, String> notifyMap) {
        Map<String,String> map = new HashMap<>();
        try {
            WXPay wxPay = new WXPay(new MyConfig());
            String code = notifyMap.get("return_code");
            if ("SUCCESS".equals(code)) {

                String out_trade_no = notifyMap.get("out_trade_no");
                System.out.println(out_trade_no);

                String total_fee = notifyMap.get("total_fee");

                PayLog payLog = payLogService.findByTransactionId(out_trade_no);
                System.out.println(payLog);

                if (payLog.getMoney().equals(Double.valueOf(total_fee))) {

                    WebSocketServer.sendInfo("SUCCESS",payLog.getOrderId());

                    payLog.setPayStatus(1);
                    long time = System.currentTimeMillis();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    payLog.setPayTime(df.parse(df.format(time)));
                    payLogService.update(payLog);

                    map.put("return_code","SUCCESS");
                    String toXml = ConvertUtils.mapToXml(map);
                    return toXml;
                }else{
                    map.put("return_code","FAIL");
                    map.put("message","订单已被篡改");
                    String toXml = ConvertUtils.mapToXml(map);
                    return toXml;
                }
            }
            return "订单生成失败!";
        } catch (Exception e) {
            e.printStackTrace();
            return "FAIL";
        }
    }
}
